package com.pojoin.cms.dao.impl.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.pojoin.cms.dao.ResourceDao;
import com.pojoin.cms.domain.Resource;
import com.pojoin.cms.domain.persistence.ResourcePersistence;
import com.pojoin.cms.util.criteria.Criteria;
import com.pojoin.cms.util.criteria.CriteriaOperator;
import com.pojoin.cms.util.criteria.impl.CriteriaKeyValue;

public class ResourceDaoImpl extends BaseDaoHibernate<ResourcePersistence> implements ResourceDao{

	private final String baseSql = "from ResourcePersistence ";
	
	@Override
	String getBaseSql() {
		return this.baseSql;
	}

	@Override
	public List<Resource> getAllResources() {
		List<Resource> rlist = new ArrayList<Resource>();
		List<ResourcePersistence> list = this.queryObjectListByCriter(null, null);
		for(Resource r : list){
			rlist.add(r);
		}
		return rlist;
	}

	@Override
	public Resource findById(Long resourceId) {
		return this.getObjectById(resourceId);
	}

	@Override
	public boolean isExist(Resource resource) {
		Criteria c = new CriteriaKeyValue("name", CriteriaOperator.EQUALS, resource.getName());
		String hql = this.getBaseSql() + " where " + c.getSQLCriteria();
		return this.objectExist(hql);
	}

	@Override
	public Resource add(Resource resource) {
		ResourcePersistence rp = new ResourcePersistence();
		BeanUtils.copyProperties(resource, rp);
		return this.insertObject(rp);
	}

	@Override
	public void delById(Long resourceId) {
		ResourcePersistence rp = this.getObjectById(resourceId);
		this.deleteObject(rp);
	}

	@Override
	public void update(Resource resource) {
		ResourcePersistence rp = this.getObjectById(resource.getResourceId());
		BeanUtils.copyProperties(resource, rp);
		this.updateObject(rp);
	}

}
